package custom.security.web.asFile;



import custom.security.exception.FileParamsException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * restful服务的文件上传和下载
 * Created by security on 2017/9/24.
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping
    public FileInfo upload(MultipartFile file) throws IOException {
        if (file==null) throw new FileParamsException("file can not be null.");

        log.info("multipartFile name:{}",file.getName());
        log.info("multipartFile filename:{}",file.getOriginalFilename());
        log.info("multipartFile size:{}",file.getSize());
        log.info("multipartFile content type:{}",file.getContentType());

        File localFile = new File(FileConstant.temp_file_dir+"\\"+System.currentTimeMillis()+".txt");

        file.transferTo(localFile);


        return new FileInfo(localFile.getAbsolutePath());
    }


    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response){
        File localFile = new File(FileConstant.temp_file_dir,id+".txt");
        try(
                FileInputStream inputStream = new FileInputStream(localFile);
                OutputStream outputStream = response.getOutputStream()) {

            response.addHeader(FileConstant.header_content_disposition,"attachment;filename=test.txt");
            response.setContentType(FileConstant.download_content_type);

            IOUtils.copy(inputStream,outputStream);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
